package com.my.yc.d0304;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.my.yc.bean.Result;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

@WebServlet(name = "OnlineServlet", value = "/OnlineServlet")
public class OnlineServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取当前在线人数
        int size = OnlineListener.onlineUsers.size();
        PrintWriter out = response.getWriter();
        JsonArray jsonArray = new JsonArray();

        Result res = new Result(1,null, null);
//        out.printf("<dl><dt>在线人数: %d</dt>", size);
        for (Map<String, Date> onlineUser : OnlineListener.onlineUsers){
            long date = ((new Date().getTime()) - onlineUser.get(onlineUser.keySet().toArray()[0].toString()).getTime()) / 1000;
            long day = date/24/60/60;
            long hour = (date-day * 24 * 60 * 60)/60/60;
            long minute =(date - day * 24 * 60 * 60 - hour * 60 * 60) / 60;
            String dif = "" + day + "天" + "  " + hour + "时" + minute + "分";
//            out.printf("<dd>%s&nbsp;&nbsp;&nbsp;&nbsp;%s</dd>",onlineUser.keySet().toArray()[0].toString(), dif);
            res.setMsg(onlineUser.keySet().toArray()[0].toString());
            res.setData(dif);
            JsonObject obj = new JsonObject();
            obj.addProperty("name", onlineUser.keySet().toArray()[0].toString());
            obj.addProperty("date", dif);
            jsonArray.add(obj);
        }
//        jsonArray.toString();
        String json = jsonArray.toString();
        out.printf(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
